const fs = require('fs')

// req.url 参数
function getUrlParam(url, param) {
  let theRequest = new Object()
  if (url.indexOf("?") != -1) {
    let str = url.split('?')[1]
    let strs = str.split("&")
    for (var i = 0; i < strs.length; i++) {
      theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1])
    }
  }
  return theRequest[param]
}
// 是否为空
function isNull(obj) {
  let result = false
  if (obj == null) result = true
  else if (obj == undefined) result = true
  else if (obj == 'null') result = true
  else if (obj == 'undefined') result = true
  else if (obj == '') result = true
  else if (obj == '[]') result = true
  else if (obj == '{}') result = true
  else if (JSON.stringify(obj) == '[]') result = true
  else if (JSON.stringify(obj) == '{}') result = true
  else if (obj == []) result = true
  else if (obj == {}) result = true
  else if (obj.length <= 0) result = true
  return result
}
// 获取文件名与扩展名
function getNameAndExt(filename) {
  let result = {}
  result.name = filename.split('').reverse().join('').split('.')[1].split('').reverse().join('')
  result.ext = filename.split('').reverse().join('').split('.')[0].split('').reverse().join('')
  return result
}
// 数组去重
function distinctArr(array) {
  let temp = []
  for (let i in array) {
    if (temp.indexOf(array[i]) == -1 && array[i].length > 0) {
      temp.push(array[i])
    }
  }
  return temp
}
// 10以内随机字符串
function randomString10(len) {
  len = len || 26
  let $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
  let maxPos = $chars.length
  let pwd = ''
  for (let i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}
/***********************************************
************************************************ 
*  本地文件操作
************************************************
************************************************/
// 判断文件夹或文件是否存在
function existsPath(path) {
  if (fs.existsSync(path)) {
    return true
  } else {
    return false
  }
}
// 判断文件夹路径是否存在并创建文件夹路径 
function mkdirPath(dirPath) {
  if (fs.existsSync(dirPath)) {
    let _stat = fs.statSync(dirPath);
    if (!(_stat.isDirectory())) {
      fs.unlinkSync(dirPath)
      fs.mkdirSync(dirPath)
    }
  } else {
    fs.mkdirSync(dirPath)
  }
  return dirPath
}
// 删除文件夹
function delDir(path) {
  let files = []
  if (fs.existsSync(path)) {
    files = fs.readdirSync(path)
    files.forEach((file, index) => {
      let curPath = path + "/" + file
      if (fs.statSync(curPath).isDirectory()) {
        delDir(curPath) //递归删除文件夹
      } else {
        fs.unlinkSync(curPath) //删除文件
      }
    });
    fs.rmdirSync(path)  // 删除文件夹自身
  }
}
// 删除文件
function delFile(path) {
  if (fs.existsSync(path)) {
    fs.unlinkSync(path)
  }
}
// 创建文件
function createFile(path, file) {
  fs.readFileSync(file[0].path, function (err, data) {
    if (err) return err
    else {
      let filepath = path + file[0].originalname
      fs.writeFileSync(filepath, data, function (err) {
        if (err) return err
        else {
          return req.files[0].originalname
        }
      })
    }
  })
}
/***********************************************
************************************************ 
*  日期时间处理
************************************************
************************************************/
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
// 日期时间格式化
function formatDateTime(date, connector) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  const millisecond = date.getMilliseconds()

  if (connector === '') {
    return [year, month, day].map(formatNumber).join('')
    + [hour, minute, second].map(formatNumber).join('')
    + [millisecond].map(formatNumber)
  } else {
    return [year, month, day].map(formatNumber).join('-')
    + ' ' + [hour, minute, second].map(formatNumber).join(':')
    + '.' + [millisecond].map(formatNumber)
  }
  
}
// 时间格式化
function formatTime(date, connector) {
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [hour, minute, second].map(formatNumber).join(connector)
}
// 日期格式化
function formatDate(date, connector) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  return [year, month, day].map(formatNumber).join(connector)
}
// 日期格式化（加减月）
function formatDateDiffMonth(date, diffMonth) {
  let diffMonthValue = diffMonth%12
  let year = date.getFullYear()
  let month = date.getMonth() + 1 + diffMonthValue
  let day = date.getDate()
	year = year + (diffMonth > 0 ? Math.floor(diffMonth/12) : Math.ceil(diffMonth/12))
	if (month > 12) {
		let monthValue = month%12
		year = year + (month > 0 ? Math.floor(month/12) : Math.ceil(month/12))
		month = monthValue
	} else if (month <= 0) {
		let monthValue = month + 12
		year = year - 1
		month = monthValue
	}
  let newdate = [year, month, day].map(formatNumber).join('-')
  const newyear = newdate.substring(0, 5)
  const newday = newdate.substring(5, newdate.length)
  if (newday == '02-28') newdate = newyear + '03-01'
  if (newday == '02-29') newdate = newyear + '03-01'
  if (newday == '02-30') newdate = newyear + '03-01'
  if (newday == '02-31') newdate = newyear + '03-01'
  if (newday == '04-31') newdate = newyear + '05-01'
  if (newday == '06-31') newdate = newyear + '07-01'
  if (newday == '09-31') newdate = newyear + '10-01'
  if (newday == '11-31') newdate = newyear + '12-01'
  return newdate
}
// 东八时间格式化
function formatGmt(datetime) {
  if (this.isNull(datetime)) return ''
  let date = datetime.indexOf('T') >= 0 ? datetime.split('T')[0] : datetime.split(' ')[0]
  let time = datetime.indexOf('T') >= 0 ? datetime.split('T')[1] : datetime.split(' ')[1]
  if (time.length <=6) time = time+':00'
  let time1 = time.split(':')[0] * 1
  time1 = time1 >= 24 ? time1 - 24 : time1
  time1 = time1 < 10 ? '0' + time1 : time1
  const time2 = time.split(':')[1]
  const time3 = time.split(':')[2].split('.')[0]
  return date + ' ' + time1 + ':' + time2 + ':' + time3
}
// 秒显示为汉字信息
function formatSeconds(s) {
  // console.log(s)
  let result = '未知时间'
  let fz = s / 60 | 0
  if (fz <= 60) {
    result = fz + '分钟'
  } else {
    let xs = s / 3600
    if (xs <= 24) {
      let xsz = xs | 0
      let xsx = (xs - xsz) * 60 | 0
      result = xsz + '小时' + xsx + '分'
    } else {
      let tian = s / 86400
      let tianz = tian | 0
      let xs = (tian - tianz) * 24
      let xsz = xs | 0
      let xsx = (xs - xsz) * 60 | 0
      result = tianz + '天' + xsz + '小时' + xsx + '分'
    }
  }
  return result
}
/***********************************************
  ************************************************ 
  *  排序
  ************************************************
  ************************************************/
// 正序
function sortAsc(arr, title) {
  if (isNull(arr)) return
  arr = arr.sort(function (a, b) {
    if (typeof (a[title]) == 'string')
      return a[title].localeCompare(b[title])
    else
      return a[title] - b[title]
  })
  return arr
}
// 逆序
function sortDesc(arr, title) {
  if (isNull(arr)) return
  arr = sortAsc(arr, title).reverse()
  return arr
}
/***********************************************
  ************************************************ 
  *  中英文判断转换
  ************************************************
  ************************************************/
// 判断是否中文英文数字
function inputJudge(v) {
  const chinese = /.*[\u4e00-\u9fa5]+.*$/
  const number = /^\d+$/
  const englishAndNum = /^[A-Za-z0-9]*$/
  if (chinese.test(v)) return '包含汉字'
  if (number.test(v)) return '只包含数字'
  if (englishAndNum.test(v)) return '包含字母或数字'
}
// 英文逗号转为中文逗号
function replaceEnglishDot(v) {
  while (v.indexOf(",") != -1) {  //寻找每一个英文逗号，并替换
    v = v.replace(",", "，")
  }
  return v
}
// 简单加密
function eazyTrans(str) {
  let s1 = '', s2 = ''
  for (let i=0;i<str.length;i++) {
    if (i%2 ==0) {
      s1 = s1 + str[i]
    } else {
      s2 = s2 + str[i]
    }
  }
  return s1.split('').reverse().join('') + s2.split('').reverse().join('')
}
// username格式检查
function nameChecked(name) {
  let result = 'success'
  name = name.toLowerCase()
  if (name[0]*0 === 0) {
    result = '用户名首位只能是字母'
  }
  let nameBase = '1234567890abcdefghijklmnopqrstuvwxyz'
  for(let i in name) {
    if (nameBase.indexOf(name[i]) < 0) {
      result = '用户名只能包含数字或字母'
    }
  }
  return result
}
// username编码
function nameEncoded(name) {
  let res = {}
  res.msg = 'success'
  name = name.toLowerCase()
  res.msg = this.nameChecked(name)
  if (res.msg  != 'success') {
    return res
  }
  let nameBase = '1234567890abcdefghijklmnopqrstuvwxyz'
  let codeBase = '0ZYX8WVU6TSR4QPO2NM9LK7JI5HG3FE1DCBA'
  let signArr = []
  for(let i in name) {
    if (nameBase.indexOf(name[i]) < 0) {
      res.msg = '用户名只能包含数字或字母'
    } else {
      signArr.push(nameBase.indexOf(name[i]))
    }
  }
  let code = ''
  for(let i in signArr) {
    code = code + codeBase[signArr[i]]
  }
  res.data = this.randomString10(80) + code
  return res
}
// username解码
function nameDecode(code) {
  let res = {}
  res.msg = 'success'
  code = code.substring(80, code.length)
  code = code.toUpperCase()
  let nameBase = '1234567890abcdefghijklmnopqrstuvwxyz'
  let codeBase = '0ZYX8WVU6TSR4QPO2NM9LK7JI5HG3FE1DCBA'
  let signArr = []
  for(let i in code) {
    if (codeBase.indexOf(code[i]) < 0) {
      res.msg = '用户名解码失败，请重试'
    } else {
      signArr.push(codeBase.indexOf(code[i]))
    }
  }
  let name = ''
  for(let i in signArr) {
    name = name + nameBase[signArr[i]]
  }
  res.data = name
  return res
}
// 控制台输出错误信息
function errConsole(tip, err) {
  console.log(this.formatDateTime(new Date()),'【ERROR ' +tip + '】 ' + err)
}

/**
 * 常量
 */
const DB_ERROR_MSG = '数据库查询错误'

module.exports = {
  getUrlParam, isNull, getNameAndExt, distinctArr, randomString10,
  existsPath, mkdirPath, delDir, delFile, createFile,
  formatDateTime, formatTime, formatDate, formatDateDiffMonth, formatGmt, formatSeconds,
  sortAsc, sortDesc, inputJudge, replaceEnglishDot, eazyTrans, 
  nameChecked, nameEncoded, nameDecode, errConsole,
  // 常量
  DB_ERROR_MSG
}